package com.lanyou.esb.cook.proxy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.lanyou.esb.cook.proxy.entity.StoreForward;

/**
 * 存储转发统计表持久层
 * 
 * @author Davey.wu
 */
public class StoreForwardDao extends BaseDao<StoreForward> {

	private static final List<String> fields = new ArrayList<String>();

	/** SQL **/
	private static final String SQL;

	static {
		fields.add("FORWARD_ID");
		fields.add("FIELD_ID");
		fields.add("FIELD_SYSTEM_ID");
		fields.add("IF_ID");
		fields.add("IF_NAME");
		fields.add("FORWARD_DATE");
		fields.add("FORWARD_TIMES");
		fields.add("FORWARD_STATUS");

		fields.add("IS_ENABLE");
		fields.add("CREATOR");
		fields.add("CREATED_DATE");
		fields.add("MODIFIER");
		fields.add("LAST_UPDATED_DATE");
	}
	static {
		StringBuilder builderFields = new StringBuilder();
		StringBuilder builderValues = new StringBuilder();
		builderFields.append(" (");
		builderValues.append(" (");
		int size = fields.size();
		for (int i = 0; i < size; ++i) {
			builderFields.append(fields.get(i) + (i == size - 1 ? "" : ","));
			builderValues.append((i == size - 1 ? "?" : "?,"));
		}
		builderFields.append(") ");
		builderValues.append(") ");
		SQL = "insert into T_ESB_BU_STORE_FORWARD" + builderFields.toString()
				+ "values " + builderValues.toString();
	}

	@Override
	public int save(StoreForward reqForward) {
		return getJdbcTemplate().update(SQL, reqForward.getId(),
				reqForward.getFieldId(), reqForward.getSystemId(),
				reqForward.getIfId(), reqForward.getIfName(),
				reqForward.getForwardDate(), reqForward.getTimes(),
				reqForward.getStatus(), reqForward.getIsEnable(),
				reqForward.getCreator(), reqForward.getCreateDate(),
				reqForward.getModifier(), reqForward.getLastUpDate());
	}

	@Override
	public int saveAll(List<StoreForward> reqForwards) {
		if (reqForwards == null || reqForwards.isEmpty()) {
			return 0;
		}
		Map<String, Boolean> idsMap = new HashMap<>();
		Map<String, Boolean> map = findIds(reqForwards);
		List<StoreForward> saves = new ArrayList<>(reqForwards.size());
		List<StoreForward> updates = new ArrayList<>(reqForwards.size());
		for (StoreForward reqForward : reqForwards) {
			// 去除重复记录
			if (idsMap.get(reqForward.getId()) != null) {
				continue;
			}
			idsMap.put(reqForward.getId(), true);
			if (map.get(reqForward.getId()) != null) {
				updates.add(reqForward);
				continue;
			}
			saves.add(reqForward);
		}

		int result = save(saves);
		result += update(updates);
		return result;
	}

	@Override
	public int update(List<StoreForward> list) {
		if (list == null || list.isEmpty()) {
			return 0;
		}
		List<Object[]> args = new ArrayList<>(list.size());
		int i = 0;
		for (StoreForward reqForward : list) {
			i = 0;
			Object[] objects = new Object[3];
			objects[i++] = reqForward.getTimes();
			objects[i++] = reqForward.getStatus();
			objects[i++] = reqForward.getId();
			args.add(objects);
		}
		String sql = "UPDATE T_ESB_BU_STORE_FORWARD SET FORWARD_TIMES=?,FORWARD_STATUS=? WHERE FORWARD_ID=?";
		int[] results = getJdbcTemplate().batchUpdate(sql, args);
		if (results == null) {
			return 0;
		}
		int result = 0;
		for (int k : results) {
			result += k;
		}
		return result;
	}

	/**
	 * 查找已存在的对象的标识
	 * 
	 * @param ids
	 * @return
	 */
	private Map<String, Boolean> findIds(List<StoreForward> reqForwards) {
		if (reqForwards == null || reqForwards.size() == 0) {
			return new HashMap<>(0);
		}
		List<String> ids = new ArrayList<>(reqForwards.size());
		for (StoreForward reqForward : reqForwards) {
			ids.add(reqForward.getId());
		}
		String sql = "SELECT t.FORWARD_ID FROM T_ESB_BU_STORE_FORWARD t WHERE t.FORWARD_ID in(:ids)";

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(
				this.getJdbcTemplate());
		List<String> result = jdbc.query(sql, paramMap,
				new RowMapper<String>() {

					@Override
					public String mapRow(ResultSet rs, int index)
							throws SQLException {
						return rs.getString("FORWARD_ID");
					}

				});
		if (result == null || result.size() == 0) {
			return new HashMap<>(0);
		}

		Map<String, Boolean> map = new HashMap<>(result.size());
		for (String id : result) {
			map.put(id, true);
		}
		return map;
	}

	/**
	 * 保存 接口访问次数统计数据
	 * 
	 * @param reqForwards
	 * @return
	 */
	private int save(List<StoreForward> reqForwards) {
		if (reqForwards == null || reqForwards.isEmpty()) {
			return 0;
		}
		List<Object[]> args = new ArrayList<>(reqForwards.size());
		int i = 0;
		for (StoreForward reqForward : reqForwards) {
			i = 0;
			Object[] objects = new Object[fields.size()];
			objects[i++] = reqForward.getId();
			objects[i++] = reqForward.getFieldId();
			objects[i++] = reqForward.getSystemId();
			objects[i++] = reqForward.getIfId();
			objects[i++] = reqForward.getIfName();
			objects[i++] = reqForward.getForwardDate();
			objects[i++] = reqForward.getTimes();
			objects[i++] = reqForward.getStatus();

			objects[i++] = reqForward.getIsEnable();
			objects[i++] = reqForward.getCreator();
			objects[i++] = reqForward.getCreateDate();
			objects[i++] = reqForward.getModifier();
			objects[i++] = reqForward.getLastUpDate();
			args.add(objects);
		}
		int[] results = getJdbcTemplate().batchUpdate(SQL, args);
		if (results == null) {
			return 0;
		}
		int result = 0;
		for (int k : results) {
			result += k;
		}
		return result;
	}
}
